"""
JH子系统 - 智能匹配API接口
提供对外的智能匹配服务接口
"""

from fastapi import APIRouter, HTTPException, Depends, Query
from typing import Dict, List, Any, Optional
from pydantic import BaseModel, Field
from datetime import datetime
import asyncio
import json

from .intelligent_matching import (
    IntelligentMatchingEngine, UserProfile, JobPosition, MatchResult,
    SkillAssessment, SkillLevel, MatchingMode, intelligent_matching_engine
)
from .enhanced_matching_service import (
    EnhancedMatchingService, MultiModalProfile, enhanced_matching_service
)

router = APIRouter(prefix="/jh/smart-matching", tags=["JH智能匹配"])

# ===== 请求和响应模型 =====

class SkillInput(BaseModel):
    """技能输入模型"""
    name: str
    level: str = Field(default="中级", description="技能水平：初级/中级/高级/专家")
    confidence: float = Field(default=0.8, ge=0, le=1, description="技能置信度")
    years_experience: int = Field(default=2, ge=0, description="使用年限")
    evidence_sources: List[str] = Field(default=[], description="证据来源")

class UserPreferences(BaseModel):
    """用户偏好模型"""
    preferred_locations: List[str] = Field(default=[], description="偏好城市")
    remote_preference: float = Field(default=0.5, ge=0, le=1, description="远程工作偏好度")
    salary_min: Optional[int] = Field(default=None, description="最低薪资期望")
    salary_max: Optional[int] = Field(default=None, description="最高薪资期望")
    salary_preferred: Optional[int] = Field(default=None, description="理想薪资")
    company_size_preference: str = Field(default="不限", description="公司规模偏好")
    industry_preferences: List[str] = Field(default=[], description="行业偏好")
    work_style_preferences: Dict[str, float] = Field(default={}, description="工作风格偏好")
    career_goals: List[str] = Field(default=[], description="职业目标")

class UserProfileInput(BaseModel):
    """用户画像输入模型"""
    user_id: str
    name: str
    skills: List[SkillInput]
    preferences: UserPreferences
    work_experience_years: int = Field(default=0, description="总工作年限")
    education_level: str = Field(default="本科", description="学历水平")
    education_school: Optional[str] = Field(default=None, description="毕业院校")
    education_major: Optional[str] = Field(default=None, description="专业")
    current_position: Optional[str] = Field(default=None, description="当前职位")
    current_salary: Optional[int] = Field(default=None, description="当前薪资")
    soft_skills: Dict[str, float] = Field(default={}, description="软技能评分")
    personality_traits: Dict[str, float] = Field(default={}, description="性格特质")

class JobPositionInput(BaseModel):
    """职位信息输入模型"""
    job_id: str
    title: str
    company: str
    description: str
    required_skills: List[Dict[str, Any]]
    preferred_skills: List[Dict[str, Any]] = Field(default=[])
    location: str
    remote_allowed: bool = Field(default=False)
    salary_min: Optional[int] = Field(default=None)
    salary_max: Optional[int] = Field(default=None)
    experience_required: int = Field(default=0, description="要求工作年限")
    education_requirement: str = Field(default="本科", description="学历要求")
    company_size: str = Field(default="不限", description="公司规模")
    industry: str = Field(default="技术", description="所属行业")
    growth_opportunities: List[str] = Field(default=[], description="成长机会")
    company_culture: Dict[str, Any] = Field(default={}, description="企业文化")

class FuzzyMatchingRequest(BaseModel):
    """模糊匹配请求"""
    user_query: str = Field(description="用户模糊需求描述")
    user_profile: Optional[UserProfileInput] = Field(default=None, description="用户画像（可选）")
    job_count_limit: int = Field(default=20, description="返回职位数量限制")
    matching_mode: str = Field(default="hybrid", description="匹配模式")

class SmartMatchingRequest(BaseModel):
    """智能匹配请求"""
    user_profile: UserProfileInput
    job_positions: List[JobPositionInput]
    matching_mode: str = Field(default="hybrid", description="匹配模式")
    analysis_depth: str = Field(default="standard", description="分析深度：basic/standard/comprehensive")

class MatchingResultResponse(BaseModel):
    """匹配结果响应"""
    job_id: str
    user_id: str
    overall_score: float
    skill_match_score: float
    culture_match_score: float
    growth_potential_score: float
    salary_match_score: float
    location_match_score: float
    confidence_level: float
    match_explanation: str
    recommendations: List[str]
    missing_skills: List[str]
    growth_path: List[str]
    detailed_analysis: Dict[str, Any]

class ComprehensiveAnalysisResponse(BaseModel):
    """综合分析响应"""
    user_id: str
    market_competitiveness: Dict[str, Any]
    skill_evolution_analysis: Dict[str, Any]
    career_progression_analysis: Dict[str, Any]
    career_trajectory_prediction: Dict[str, Any]
    strategic_recommendations: List[str]
    comprehensive_score: Dict[str, float]
    analysis_timestamp: str

# ===== 辅助函数 =====

def convert_user_input_to_profile(user_input: UserProfileInput) -> UserProfile:
    """将输入模型转换为内部UserProfile"""
    
    # 转换技能
    skills = []
    for skill_input in user_input.skills:
        skill_level = SkillLevel.INTERMEDIATE  # 默认中级
        for level in SkillLevel:
            if level.value == skill_input.level:
                skill_level = level
                break
        
        skill_assessment = SkillAssessment(
            skill_name=skill_input.name,
            proficiency_level=skill_level,
            confidence_score=skill_input.confidence,
            market_demand=0.8,  # 默认市场需求
            skill_weight=0.8,   # 默认技能权重
            related_skills=[],  # 暂时为空
            evidence_sources=skill_input.evidence_sources
        )
        skills.append(skill_assessment)
    
    # 构建偏好字典
    preferences = {
        "location": {
            "preferred_cities": user_input.preferences.preferred_locations,
            "remote_preference": user_input.preferences.remote_preference
        },
        "salary_expectations": {
            "min": user_input.preferences.salary_min,
            "max": user_input.preferences.salary_max,
            "preferred": user_input.preferences.salary_preferred
        },
        "work_style": user_input.preferences.work_style_preferences,
        "career_goals": user_input.preferences.career_goals,
        "company_size": user_input.preferences.company_size_preference,
        "industry_preferences": user_input.preferences.industry_preferences
    }
    
    # 构建教育背景
    education = {
        "degree_level": user_input.education_level,
        "university": user_input.education_school or "",
        "major": user_input.education_major or ""
    }
    
    # 构建工作经历（简化）
    experience = [{
        "title": user_input.current_position or "未知职位",
        "duration_years": user_input.work_experience_years,
        "salary": user_input.current_salary
    }]
    
    # 默认软技能
    default_soft_skills = {
        "沟通能力": 0.7,
        "团队协作": 0.7,
        "学习能力": 0.8,
        "领导力": 0.6,
        "创新能力": 0.7
    }
    soft_skills = {**default_soft_skills, **user_input.soft_skills}
    
    # 默认性格特质
    default_personality = {
        "openness": 0.7,
        "conscientiousness": 0.7,
        "extraversion": 0.6,
        "agreeableness": 0.7,
        "neuroticism": 0.4
    }
    personality_traits = {**default_personality, **user_input.personality_traits}
    
    return UserProfile(
        user_id=user_input.user_id,
        name=user_input.name,
        education=education,
        experience=experience,
        skills=skills,
        soft_skills=soft_skills,
        preferences=preferences,
        behavioral_data={},
        personality_traits=personality_traits,
        career_trajectory=[]
    )

def convert_job_input_to_position(job_input: JobPositionInput) -> JobPosition:
    """将输入模型转换为内部JobPosition"""
    
    # 构建薪资信息
    compensation = {
        "min": job_input.salary_min,
        "max": job_input.salary_max,
        "benefits": {}
    }
    
    # 构建企业文化
    company_culture = {
        **job_input.company_culture,
        "work_environment": {},
        "personality_requirements": {},
        "team_dynamics": {}
    }
    
    # 构建软技能要求（默认）
    soft_skill_requirements = {
        "沟通能力": 0.7,
        "团队协作": 0.8,
        "学习能力": 0.7,
        "抗压能力": 0.6
    }
    
    return JobPosition(
        job_id=job_input.job_id,
        title=job_input.title,
        company=job_input.company,
        description=job_input.description,
        required_skills=job_input.required_skills,
        preferred_skills=job_input.preferred_skills,
        soft_skill_requirements=soft_skill_requirements,
        company_culture=company_culture,
        compensation=compensation,
        location=job_input.location,
        remote_options=job_input.remote_allowed,
        growth_opportunities=job_input.growth_opportunities
    )

def convert_match_result_to_response(result: MatchResult) -> MatchingResultResponse:
    """将内部MatchResult转换为响应模型"""
    return MatchingResultResponse(
        job_id=result.job_id,
        user_id=result.user_id,
        overall_score=result.overall_score,
        skill_match_score=result.skill_match_score,
        culture_match_score=result.culture_match_score,
        growth_potential_score=result.growth_potential_score,
        salary_match_score=result.salary_match_score,
        location_match_score=result.location_match_score,
        confidence_level=result.confidence_level,
        match_explanation=result.match_explanation,
        recommendations=result.recommendations,
        missing_skills=result.missing_skills,
        growth_path=result.growth_path,
        detailed_analysis=result.detailed_analysis
    )

# ===== API 接口 =====

@router.post("/comprehensive-matching", response_model=List[MatchingResultResponse])
async def comprehensive_matching(request: SmartMatchingRequest):
    """
    综合智能匹配
    
    执行多维度智能评分和匹配分析，返回详细的匹配结果
    """
    try:
        # 转换输入数据
        user_profile = convert_user_input_to_profile(request.user_profile)
        job_positions = [convert_job_input_to_position(job) for job in request.job_positions]
        
        # 确定匹配模式
        matching_mode = MatchingMode.HYBRID
        for mode in MatchingMode:
            if mode.value == request.matching_mode:
                matching_mode = mode
                break
        
        # 执行匹配
        results = await intelligent_matching_engine.comprehensive_matching(
            user_profile, job_positions, matching_mode
        )
        
        # 转换结果
        response_results = [convert_match_result_to_response(result) for result in results]
        
        return response_results
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"匹配分析失败: {str(e)}")

@router.post("/fuzzy-matching", response_model=List[MatchingResultResponse])
async def fuzzy_matching(request: FuzzyMatchingRequest):
    """
    模糊匹配
    
    基于用户的模糊需求描述进行智能匹配
    """
    try:
        # 模拟获取职位数据（实际应该从数据库获取）
        sample_jobs = await _get_sample_job_positions(request.job_count_limit)
        
        # 执行模糊匹配
        results = await intelligent_matching_engine.fuzzy_matching(
            request.user_query, sample_jobs
        )
        
        # 转换结果
        response_results = [convert_match_result_to_response(result) for result in results]
        
        return response_results
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"模糊匹配失败: {str(e)}")

@router.post("/comprehensive-analysis", response_model=ComprehensiveAnalysisResponse)
async def comprehensive_analysis(user_profile: UserProfileInput):
    """
    综合分析
    
    对用户进行全面的市场竞争力、技能发展、职业轨迹分析
    """
    try:
        # 转换用户画像
        profile = convert_user_input_to_profile(user_profile)
        
        # 执行综合分析
        analysis_result = await enhanced_matching_service.comprehensive_analysis(profile)
        
        response = ComprehensiveAnalysisResponse(
            user_id=profile.user_id,
            market_competitiveness=analysis_result["market_competitiveness"],
            skill_evolution_analysis=analysis_result["skill_evolution_analysis"],
            career_progression_analysis=analysis_result["career_progression_analysis"],
            career_trajectory_prediction=analysis_result["career_trajectory_prediction"],
            strategic_recommendations=analysis_result["strategic_recommendations"],
            comprehensive_score=analysis_result["comprehensive_score"],
            analysis_timestamp=datetime.now().isoformat()
        )
        
        return response
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"综合分析失败: {str(e)}")

@router.get("/skill-similarity")
async def calculate_skill_similarity(
    skill1: str = Query(description="技能1"),
    skill2: str = Query(description="技能2")
):
    """
    计算技能相似度
    
    返回两个技能之间的语义相似度分数
    """
    try:
        similarity = intelligent_matching_engine.skill_analyzer.analyze_skill_similarity(skill1, skill2)
        
        return {
            "skill1": skill1,
            "skill2": skill2,
            "similarity_score": similarity,
            "similarity_level": _get_similarity_level(similarity)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"技能相似度计算失败: {str(e)}")

@router.get("/market-trends")
async def get_market_trends(skill: Optional[str] = Query(default=None, description="技能名称")):
    """
    获取市场趋势信息
    
    返回技能市场价值和趋势数据
    """
    try:
        if skill:
            # 获取特定技能的市场价值
            market_value = intelligent_matching_engine.market_analyzer.get_skill_market_value(skill)
            return {
                "skill": skill,
                "market_data": market_value,
                "analysis_date": datetime.now().isoformat()
            }
        else:
            # 返回整体市场趋势
            trend_data = intelligent_matching_engine.market_analyzer.skill_demand_trends
            return {
                "overall_trends": trend_data,
                "analysis_date": datetime.now().isoformat()
            }
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"市场趋势获取失败: {str(e)}")

@router.post("/batch-matching")
async def batch_matching(
    user_profiles: List[UserProfileInput],
    job_positions: List[JobPositionInput],
    max_matches_per_user: int = Query(default=5, description="每个用户最大匹配数")
):
    """
    批量匹配
    
    对多个用户和多个职位进行批量匹配分析
    """
    try:
        batch_results = {}
        
        for user_input in user_profiles:
            user_profile = convert_user_input_to_profile(user_input)
            job_positions_converted = [convert_job_input_to_position(job) for job in job_positions]
            
            # 执行匹配
            results = await intelligent_matching_engine.comprehensive_matching(
                user_profile, job_positions_converted, MatchingMode.HYBRID
            )
            
            # 取前N个最佳匹配
            top_matches = results[:max_matches_per_user]
            batch_results[user_input.user_id] = [
                convert_match_result_to_response(result) for result in top_matches
            ]
        
        return {
            "batch_results": batch_results,
            "processed_users": len(user_profiles),
            "processed_jobs": len(job_positions),
            "analysis_timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量匹配失败: {str(e)}")

@router.get("/matching-statistics")
async def get_matching_statistics():
    """
    获取匹配统计信息
    
    返回系统的匹配统计数据和性能指标
    """
    try:
        # 模拟统计数据（实际应该从数据库或缓存获取）
        stats = {
            "total_matches_performed": 1250,
            "average_match_score": 0.73,
            "top_performing_skills": ["Python", "机器学习", "React", "云计算"],
            "most_matched_industries": ["人工智能", "金融科技", "电商", "企业服务"],
            "average_processing_time_ms": 150,
            "user_satisfaction_rate": 0.89,
            "last_updated": datetime.now().isoformat()
        }
        
        return stats
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"统计信息获取失败: {str(e)}")

# ===== 辅助函数 =====

async def _get_sample_job_positions(limit: int) -> List[JobPosition]:
    """获取示例职位数据（用于模糊匹配）"""
    # 在实际应用中，这里应该从数据库获取真实的职位数据
    sample_jobs = []
    
    for i in range(min(limit, 20)):
        job = JobPosition(
            job_id=f"job_{i+1}",
            title=f"高级软件工程师 {i+1}",
            company=f"科技公司 {i+1}",
            description="负责产品核心功能开发，参与系统架构设计",
            required_skills=[
                {"name": "Python", "level": "高级", "weight": 1.0},
                {"name": "JavaScript", "level": "中级", "weight": 0.8}
            ],
            preferred_skills=[
                {"name": "机器学习", "level": "中级", "weight": 0.6}
            ],
            soft_skill_requirements={"沟通能力": 0.7, "团队协作": 0.8},
            company_culture={"work_environment": {"remote_friendly": True}},
            compensation={"min": 150000, "max": 250000},
            location="北京" if i % 2 == 0 else "上海",
            remote_options=True,
            growth_opportunities=["技术专家", "团队管理", "架构师"]
        )
        sample_jobs.append(job)
    
    return sample_jobs

def _get_similarity_level(score: float) -> str:
    """根据相似度分数返回相似度等级"""
    if score >= 0.9:
        return "极高相似"
    elif score >= 0.8:
        return "高度相似"
    elif score >= 0.7:
        return "中等相似"
    elif score >= 0.5:
        return "低度相似"
    else:
        return "不相似" 